#!/usr/bin/env bash

source ./config/env.sh
clear

mkdir -p ${K8S_CA_DIR}/apiserver

cat > ${K8S_CA_DIR}/apiserver/kubernetes-csr.json <<EOF
{
  "CN": "kubernetes",
  "hosts": [
    "127.0.0.1",
    "${APISERVER_VIP}",
    "${CLUSTER_KUBERNETES_SVC_IP}",
    "kubernetes",
    "kubernetes.default",
    "kubernetes.default.svc",
    "kubernetes.default.svc.cluster",
    "kubernetes.default.svc.cluster.local"
  ],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "ST": "BeiJing",
      "L": "BeiJing",
      "O": "k8s",
      "OU": "4Paradigm"
    }
  ]
}
EOF

for master_ip in ${MASTER_IP}
do
    sed -i '5 i\ \ \ \ "'${master_ip}'",' ${K8S_CA_DIR}/apiserver/kubernetes-csr.json
done

cd ${K8S_CA_DIR}/apiserver

cfssl gencert -ca=${K8S_CA_DIR}/admin/ca.pem \
    -ca-key=${K8S_CA_DIR}/admin/ca-key.pem \
    -config=${K8S_CA_DIR}/admin/ca-config.json \
    -profile=kubernetes kubernetes-csr.json | cfssljson -bare kubernetes

mkdir -p ${K8S_DATA}/config/apiserver/yaml

cat > ${K8S_DATA}/config/apiserver/yaml/encryption-config.yaml <<EOF
kind: EncryptionConfig
apiVersion: v1
resources:
  - resources:
      - secrets
    providers:
      - aescbc:
          keys:
            - name: key1
              secret: ${ENCRYPTION_KEY}
      - identity: {}
EOF

for master_ip in ${MASTER_IP}
do
    echo "=========================================== ${master_ip} ==========================================="
    ssh root@${master_ip} "test -e ${K8S_CA_DIR}/apiserver || mkdir -p ${K8S_CA_DIR}/apiserver"
    scp ${K8S_CA_DIR}/apiserver/kubernetes*.pem root@${master_ip}:${K8S_CA_DIR}/apiserver
    ssh root@${master_ip} "test -e ${K8S_DATA}/config/apiserver/yaml || mkdir -p ${K8S_DATA}/config/apiserver/yaml"
    scp ${K8S_DATA}/config/apiserver/yaml/encryption-config.yaml root@${master_ip}:${K8S_DATA}/config/apiserver/yaml
    ssh root@${master_ip} "mkdir -p ${K8S_LOGS_DIR}/apiserver/"
done


cat > ${K8S_DATA}/config/apiserver/kube-apiserver.service.template <<EOF
[Unit]
Description=k8s APIServer
Documentation=https://github.com/GoogleCloudPlatform/kubernetes
After=network.target
[Service]
WorkingDirectory=${K8S_DATA}/data/apiserver
ExecStart=${K8S_BIN_DIR}/kube-apiserver \\
  --enable-admission-plugins=Initializers,NamespaceLifecycle,NodeRestriction,LimitRanger,ServiceAccount,DefaultStorageClass,ResourceQuota \\
  --anonymous-auth=false \\
  --experimental-encryption-provider-config=${K8S_DATA}/config/apiserver/yaml/encryption-config.yaml \\
  --advertise-address=##NODE_IP## \\
  --bind-address=##NODE_IP## \\
  --insecure-port=0 \\
  --authorization-mode=Node,RBAC \\
  --runtime-config=api/all \\
  --enable-bootstrap-token-auth \\
  --service-cluster-ip-range=${SERVICE_CIDR} \\
  --service-node-port-range=${NODE_PORT_RANGE} \\
  --tls-cert-file=${K8S_CA_DIR}/apiserver/kubernetes.pem \\
  --tls-private-key-file=${K8S_CA_DIR}/apiserver/kubernetes-key.pem \\
  --client-ca-file=${K8S_CA_DIR}/admin/ca.pem \\
  --kubelet-client-certificate=${K8S_CA_DIR}/apiserver/kubernetes.pem \\
  --kubelet-client-key=${K8S_CA_DIR}/apiserver/kubernetes-key.pem \\
  --service-account-key-file=${K8S_CA_DIR}/admin/ca-key.pem \\
  --etcd-cafile=${K8S_CA_DIR}/admin/ca.pem \\
  --etcd-certfile=${K8S_CA_DIR}/apiserver/kubernetes.pem \\
  --etcd-keyfile=${K8S_CA_DIR}/apiserver/kubernetes-key.pem \\
  --etcd-servers=${ETCD_NODES} \\
  --enable-swagger-ui=true \\
  --allow-privileged=true \\
  --max-mutating-requests-inflight=2000 \\
  --max-requests-inflight=4000 \\
  --apiserver-count=${MASTER} \\
  --audit-log-maxage=30 \\
  --audit-log-maxbackup=3 \\
  --audit-log-maxsize=100 \\
  --audit-log-path=${K8S_LOGS_DIR}/apiserver/audit.log \\
  --event-ttl=168h \\
  --alsologtostderr=true \\
  --logtostderr=false \\
  --v=2                \\
  --requestheader-client-ca-file=${K8S_CA_DIR}/admin/ca.pem    \\
  --requestheader-allowed-names="aggregator"                    \\
  --requestheader-extra-headers-prefix="X-Remote-Extra-"          \\
  --requestheader-group-headers=X-Remote-Group                     \\
  --requestheader-username-headers=X-Remote-User                    \\
  --proxy-client-cert-file=${K8S_CA_DIR}/metrics-server/metrics-server.pem   \\
  --proxy-client-key-file=${K8S_CA_DIR}/metrics-server/metrics-server-key.pem \\
  --runtime-config=api/all=true

Restart=on-failure
RestartSec=5
Type=notify
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF



for (( i=1; i <= ${MASTER} ; i++ ))
do
    sed -e "s/##NODE_NAME##/`echo ${MASTER_HOSTNAME} | cut -d " " -f $i`/" -e "s/##NODE_IP##/`echo ${MASTER_IP} | cut -d " " -f $i`/" ${K8S_DATA}/config/apiserver/kube-apiserver.service.template > ${K8S_DATA}/config/apiserver/kube-apiserver-`echo ${MASTER_IP} | cut -d " " -f $i`.service
done

for master_ip in ${MASTER_IP}
do
  echo "=========================================== ${master_ip} ==========================================="
  ssh root@${master_ip} "test -e ${K8S_LOGS_DIR}/apiserver || mkdir -p ${K8S_LOGS_DIR}/apiserver"
  scp ${K8S_DATA}/config/apiserver/kube-apiserver-${master_ip}.service root@${master_ip}:/etc/systemd/system/kube-apiserver.service
done

for master_ip in ${MASTER_IP}
do
  echo "=========================================== ${master_ip} ==========================================="
  ssh root@${master_ip} "test -e ${K8S_DATA}/data/apiserver || mkdir -p ${K8S_DATA}/data/apiserver"
  ssh root@${master_ip} "systemctl daemon-reload && systemctl enable kube-apiserver && systemctl start kube-apiserver"
done

sleep 10

for master_ip in ${MASTER_IP}
do
  echo "=========================================== ${master_ip} ==========================================="
  ssh root@${master_ip} "systemctl status  kube-apiserver | grep 'Active:'"
done

# test
ETCDCTL_API=3 ${K8S_BIN_DIR}/etcdctl \
    --endpoints=${ETCD_NODES} \
    --cacert=${K8S_CA_DIR}/admin/ca.pem \
    --cert=${K8S_CA_DIR}/etcd/etcd.pem \
    --key=${K8S_CA_DIR}/etcd/etcd-key.pem \
    get /registry/ --prefix --keys-only

${K8S_BIN_DIR}/kubectl cluster-info
${K8S_BIN_DIR}/kubectl get all --all-namespaces
${K8S_BIN_DIR}/kubectl get componentstatuses

${K8S_BIN_DIR}/kubectl create clusterrolebinding kube-apiserver:kubelet-apis --clusterrole=system:kubelet-api-admin --user kubernetes